/* g++ -o wc wc.cpp */

#include <cstdio>

#include <unistd.h>
#include <stdlib.h>

#include <string>
using std::string;
#include "utf8_string.h"

int check_and_count_utf8char(const string& str) {
    utf8_string utf8string;
    int nlinechar = utf8string.from_bytes(str.c_str());
    if (nlinechar == -1) {
        printf("Error: input file is not utf8 encoded\n");
        exit(1);
    }
    return nlinechar;
}

bool is_white(const char c) {
    return c == ' ' || c == '\t' || c == '\n';
}
int main(int argc, char *argv[]) {

    // Handle arguments
    bool is_showlines = false;
    bool is_showwords = false;
    bool is_showbytes = false;
    bool is_showchars = false;
    bool is_show_maxlinelen = false;
    int opt;
    while ((opt = getopt(argc, argv, "cmlLw")) != -1) {
        switch (opt) {
        case 'c':
            is_showbytes = true;
            break;
        case 'm':
            is_showchars = true;
            break;
        case 'l':
            is_showlines = true;
            break;
        case 'L':
            is_show_maxlinelen = true;
            break;
        case 'w':
            is_showwords = true;
            break;
        default: /* '?' */
            fprintf(stderr, "Usage: %s [-c] [-m] [-l] [-L] [-w]\n",
                    argv[0]);
            exit(EXIT_FAILURE);
        }
    }

    char c;
    int nline = 0, nword = 0, nchar = 0, maxlinelen = 0, nbyte = 0;
    int curr_linelen = 0;
    bool scanning_word = false;
    string curr_line;
    while ( (c = getchar()) != EOF) {
        nbyte++;
        curr_line += c;
        if (c == '\n') {
            nline++;
            curr_linelen = check_and_count_utf8char(curr_line);
            nchar += curr_linelen;
            curr_linelen--; // max length len not countting the last \n
            if (curr_linelen > maxlinelen)
                maxlinelen = curr_linelen;
            curr_line = "";
        }
        if (is_white(c) && scanning_word) {
            scanning_word = false;
            nword++;
        }
        else if (!is_white(c) && !scanning_word)
            scanning_word = true;
    }
    if (scanning_word)
        nword++;
    curr_linelen = check_and_count_utf8char(curr_line);
    if (curr_linelen > maxlinelen)
        maxlinelen = curr_linelen;
    nchar += curr_linelen;

    if (argc == 1)
        printf("%d %d %d\n", nline, nword, nbyte);
    else {
        if (is_showlines)
            printf(" %d", nline);
        if (is_showwords)
            printf(" %d", nword);
        if (is_showchars)
            printf(" %d", nchar);
        if (is_showbytes)
            printf(" %d", nbyte);
        if (is_show_maxlinelen)
            printf(" %d", maxlinelen);
        printf("\n");
    }

    return 0;
}
